from flask import jsonify, request, Response
import time
from config import logger

class ApiRoutes:
    def __init__(self, app, joystick_manager, robot_controller, camera_manager):
        self.app = app
        self.joystick_manager = joystick_manager
        self.robot_controller = robot_controller
        self.camera_manager = camera_manager
        
        # 注册API路由
        self.register_routes()
    
    def register_routes(self):
        # 视频流
        self.app.route('/video_feed')(self.video_feed)
        
        # 手柄数据接口
        self.app.route('/joystick', methods=['POST'])(self.receive_joystick)
        self.app.route('/joystick/latest', methods=['GET'])(self.get_latest_joystick)
        self.app.route('/joystick/data', methods=['GET'])(self.get_joystick_data)
        
        # 机器人控制接口
        self.app.route('/robot/start', methods=['POST'])(self.start_robot)
        self.app.route('/robot/stop', methods=['POST'])(self.stop_robot)
        self.app.route('/robot/status', methods=['GET'])(self.robot_status)
        
        # 服务器状态接口
        self.app.route('/status', methods=['GET'])(self.get_status)
    
    def video_feed(self):
        """提供视频流"""
        return Response(
            self.camera_manager.generate_frames(),
            mimetype='multipart/x-mixed-replace; boundary=frame'
        )
    
    def receive_joystick(self):
        """接收手柄数据的API端点"""
        try:
            # 获取JSON数据
            data = request.get_json()
            
            if not data:
                return jsonify({"status": "error", "message": "没有接收到数据"}), 400
            
            # 验证数据格式
            required_fields = ["left_x", "left_y", "right_x", "right_y", "timestamp"]
            for field in required_fields:
                if field not in data:
                    return jsonify({"status": "error", "message": f"缺少必填字段: {field}"}), 400
            
            # 处理数据
            self.joystick_manager.process_joystick_data(data)
            
            return jsonify({"status": "success", "message": "手柄数据已接收"}), 200
        
        except Exception as e:
            logger.error(f"处理手柄数据时出错: {str(e)}")
            return jsonify({"status": "error", "message": f"处理数据时出错: {str(e)}"}), 500
    
    def get_latest_joystick(self):
        """获取最新的手柄数据"""
        data = self.joystick_manager.get_latest_data()
        if data:
            return jsonify(data)
        else:
            return jsonify(None)
    
    def get_joystick_data(self):
        """获取所有手柄数据的JSON"""
        return jsonify(self.joystick_manager.get_all_data())
    
    def start_robot(self):
        """启动机器人控制"""
        if not self.robot_controller.is_available():
            return jsonify({"status": "error", "message": "Raspbot库未找到，无法控制机器人"}), 400
            
        success = self.robot_controller.start_control()
        if success:
            return jsonify({"status": "success", "message": "机器人控制已启动"}), 200
        else:
            return jsonify({"status": "error", "message": "机器人控制已在运行中"}), 400
    
    def stop_robot(self):
        """停止机器人控制"""
        success = self.robot_controller.stop_control()
        if success:
            return jsonify({"status": "success", "message": "机器人控制已停止"}), 200
        else:
            return jsonify({"status": "error", "message": "机器人控制未在运行"}), 400
    
    def robot_status(self):
        """获取机器人控制状态"""
        return jsonify({
            "running": self.robot_controller.is_running(),
            "robot_available": self.robot_controller.is_available()
        })
    
    def get_status(self):
        """获取服务器状态"""
        status = {
            "status": "running",
            "time": time.strftime("%Y-%m-%d %H:%M:%S"),
            "joystick_data_count": len(self.joystick_manager.get_all_data()),
            "latest_joystick": self.joystick_manager.get_latest_data(),
            "robot_control": {
                "running": self.robot_controller.is_running(),
                "robot_available": self.robot_controller.is_available()
            }
        }
        return jsonify(status)
